package com.naiterui.ehp.bs.recommend.service.impl;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.naiterui.ehp.bp.bo.b2c.cms.MedicineBO;
import com.naiterui.ehp.bp.bo.b2c.order.OrderBO;
import com.naiterui.ehp.bp.bo.consult.VideoConsultBO;
import com.naiterui.ehp.bp.bo.doctor.DoctorBO;
import com.naiterui.ehp.bp.bo.patient.PatientInquirerBO;
import com.naiterui.ehp.bp.bo.pharmacist.PharmacistInfoBO;
import com.naiterui.ehp.bp.constants.SuperviseConstant;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.utils.date.DateUtil;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;
import com.naiterui.ehp.bs.recommend.bean.*;
import com.naiterui.ehp.bs.recommend.remote.*;
import com.naiterui.ehp.bs.recommend.repository.mysql.*;
import com.naiterui.ehp.bs.recommend.service.IRecomSuperviseService;
import com.naiterui.ehp.bs.recommend.util.Constants;
import com.naiterui.ehp.bs.recommend.vo.*;

import cn.hutool.core.collection.CollectionUtil;

/**
 * <pre>
 * 监管相关数据查询
 * </pre>
 *
 * @author fangguanhong
 * @date 2021/1/14 上午10:51
 * @since 1.0.0
 */
@Service
public class RecomSuperviseServiceImpl implements IRecomSuperviseService {

    @Autowired
    private IMedicationRecomRepository medicationRecomRepository;
    @Autowired
    private IMedicationRecomDetailRepository medicationRecomDetailRepository;
    @Autowired
    private IMedicationRecomDiagnosisRepository medicationRecomDiagnosisRepository;
    @Autowired
    private IMedicationRecomInfoRepository medicationRecomInfoRepository;
    @Autowired
    private IDrStandardDiagnosisRepository standardDiagnosisRepository;
    @Autowired
    private IRecommPrescriptionRepository recommPrescriptionRepository;
    @Autowired
    private IB2cFeignClient b2cFeignClient;
    @Autowired
    private IPharmacistFeignClient pharmacistFeignClient;

    private String IMG_URL = ConfigUtil.getString("img.domain");

    @Autowired
    private VideoConsultFeignClient videoConsultFeignClient;
    @Autowired
    private IRecomAuditLogRepository recommissionLogRepository;
    @Autowired
    private IDoctorFeignClient doctorFeignClient;
    @Autowired
    private IPatientFeignClient patientFeignClient;

    @Override
    public List<SuperviseRecomVO> sessionRecoms(Long sessionId) {
        List<SuperviseRecomVO> result = new ArrayList<>();
        List<MedicationRecom> medicationRecoms = medicationRecomRepository.findBySessionId(sessionId);
        List<Long> recomIds = new ArrayList<>();
        recomIds = medicationRecoms.stream().map(recom -> recom.getId()).collect(Collectors.toList());

        // 处方药品明细
        List<MedicationRecomDetail> recomDetails = medicationRecomDetailRepository.findByRecommendIdIn(recomIds);
        Map<Long, List<MedicationRecomDetail>> recomDetailMap =
                recomDetails.stream().collect(Collectors.groupingBy(MedicationRecomDetail::getRecommendId));
        List<DrMedicationRecomDiagnosis> recomDiagnoses = medicationRecomDiagnosisRepository.findByRecommendIdIn(recomIds);
        Map<Long, List<DrMedicationRecomDiagnosis>> recomDiagnosisMap =
                recomDiagnoses.stream().collect(Collectors.groupingBy(DrMedicationRecomDiagnosis::getRecommendId));
        List<Long> diagnoseIds = recomDiagnoses.stream().map(diagnose -> diagnose.getDiagnosisId()).collect(Collectors.toList());
        List<DrStandardDiagnosis> diagnoses = standardDiagnosisRepository.findByIdIn(diagnoseIds);
        Map<Long, DrStandardDiagnosis> diagnosisMap = diagnoses.stream().collect(Collectors.toMap(DrStandardDiagnosis::getId, e -> e));

        // 处方信息
        List<DrMedicationRecomInfo> medicationRecomInfos = medicationRecomInfoRepository.findByRecommendIdIn(recomIds);
        Map<Long, DrMedicationRecomInfo> medicationRecomInfosMap =
                medicationRecomInfos.stream().collect(Collectors.toMap(DrMedicationRecomInfo::getRecommendId, e -> e));

        // 药师ID列表
        List<Long> pharmacistIds = medicationRecomInfos.stream().map(info -> info.getPharmacistId()).collect(Collectors.toList());
        // 批量获取药师信息
        List<PharmacistInfoBO> pharmacistInfoBOS = pharmacistFeignClient.getPharmacistInfoList(pharmacistIds);
        Map<Long, PharmacistInfoBO> pharmacistInfoMap = pharmacistInfoBOS.stream().collect(Collectors.toMap(PharmacistInfoBO::getId, e -> e));

        // 处方签名文件
        List<RecomPrescription> recomPrescriptions = recommPrescriptionRepository.findByRecommendIdInAndType(recomIds,
                RecomPrescription.TYPE_PHARMACIST_SIGN);
        Map<Long, RecomPrescription> recomPrescriptionMap = recomPrescriptions.stream()
                                                                              .collect(Collectors.toMap(RecomPrescription::getRecommendId, e -> e));

        if (CollectionUtil.isNotEmpty(medicationRecoms)) {
            medicationRecoms.forEach(recom -> {
                DrMedicationRecomInfo medicationRecomInfo = medicationRecomInfosMap.get(recom.getId());
                PharmacistInfoBO pharmacistInfo = pharmacistInfoMap.get(medicationRecomInfo.getPharmacistId());
                SuperviseRecomVO vo =
                        SuperviseRecomVO.builder()
                                        .id(recom.getId())
                                        .createdAt(DateUtil.formatDate(recom.getCreatedAt(), DateUtil.DATE_TIME_FORMAT))
                                        .effectiveDays(7)
                                        .serviceTime(DateUtil.formatDate(recom.getCreatedAt(), DateUtil.DATE_TIME_FORMAT))
                                        .doctorsSummary(null)
                                        .pharmacistId(medicationRecomInfo.getPharmacistId())
                                        .pharmacistName(medicationRecomInfo.getPharmacistName())
                                        .pharmacistLicenseNo(null != pharmacistInfo ? pharmacistInfo.getLicenseNo() : null)
                                        .dataAt(DateUtil.formatDate(recom.getCreatedAt(), DateUtil.DATE_TIME_FORMAT))
                                        .auditAt(null != medicationRecomInfo.getDoctorSignTime() ?
                                                DateUtil.formatDate(medicationRecomInfo.getDoctorSignTime(),
                                                        DateUtil.DATE_TIME_FORMAT) : null)
                                        //.diagnosisId(recomDiagnosisMap.get(recom.getId()).getDiagnosisId())
                                        //.diagnosisCode(diagnosisMap.get(recomDiagnosisMap.get(recom.getId()).getDiagnosisId()).getMainCode())
                                        //.diagnosisName(diagnosisMap.get(recomDiagnosisMap.get(recom.getId()).getDiagnosisId()).getName())
                                        .pdfUrl(null != recomPrescriptionMap.get(recom.getId()) ?
                                                IMG_URL + recomPrescriptionMap.get(recom.getId()).getPrescriptionPhotoUrl() : null)
                                        .build();
                if (null != recomDiagnosisMap.get(recom.getId())) {

                    List<DrMedicationRecomDiagnosis> diagnosisList = recomDiagnosisMap.get(recom.getId());
                    vo.setDiagnosis(
                            diagnosisList.stream().map(diag -> {
                                DrStandardDiagnosis diagno = diagnosisMap.get(diag.getDiagnosisId());
                                return SuperviseDiagnosisVO.builder().id(diagno.getId()).code(diagno.getMainCode()).name(diagno.getName()).build();
                            }).collect(Collectors.toList()));
                }

                // 药品信息
                List<SuperviseProductVO> products = new ArrayList<>();
                List<MedicationRecomDetail> details = recomDetailMap.get(recom.getId());
                List<Long> skuIds = details.stream().map(sk -> sk.getSkuId()).collect(Collectors.toList());
                details.forEach(detail -> {
                    SuperviseProductVO productVO =
                            SuperviseProductVO.builder()
                                              .skuId(detail.getSkuId())
                                              .name(detail.getName())
                                              .commonName(detail.getCommonName())
                                              .dosageCount(detail.getDosageCount())
                                              .dosageCycleUnit(detail.getDosageCycleUnit())
                                              .dosageCycle(detail.getDosageCycle().toString())
                                              .eachDosageCount(detail.getEachDosageCount())
                                              .eachDoseUnit(detail.getEachDoseUnit())
                                              .drugCycle(detail.getDrugCycle())
                                              .drugCycleUnit(detail.getDrugCycleUnit())
                                              .usageMethod(detail.getUsageMethod())
                                              .quantity(detail.getQuantity())
                                              .quantityUnit(detail.getQuantityUnit())
                                              .salePrice(detail.getSalePrice())
                                              .totalPrice(detail.getSalePrice() * detail.getQuantity())
                                              .usageTime(detail.getUsageTime())
                                              .build();
                    products.add(productVO);
                });

                List<SuperviseSkuVO> skuInfo = b2cFeignClient.recomProduct(skuIds);
                Map<Long, SuperviseSkuVO> skuVOMap = skuInfo.stream().collect(Collectors.toMap(SuperviseSkuVO::getSkuId, e -> e));

                products.forEach(product -> {
                    SuperviseSkuVO sku = skuVOMap.get(product.getSkuId());
                    product.setId(sku.getSkuId().toString());
                    product.setSpec(sku.getSpec());
                    product.setPillCode(sku.getPillCode());
                    product.setPillName(sku.getPillName());
                    product.setPackingUnit(sku.getPackingUnit());
                });
                vo.setProducts(products);
                vo.setTotalPrice(details.stream().collect(Collectors.summingInt(detail -> detail.getQuantity() * detail.getSalePrice())));

                result.add(vo);
            });
        }

        return result;
    }

    @Override
    public PrescriptionVO getPrescription(Long sessionId) {
        List<String> pdfUrls = new ArrayList<>();
        List<MedicationRecom> medicationRecoms = medicationRecomRepository.findBySessionId(sessionId);
        List<Long> recomIds = new ArrayList<>();
        recomIds = medicationRecoms.stream().map(recom -> recom.getId()).collect(Collectors.toList());

        // 处方签名文件
        List<RecomPrescription> recomPrescriptions = recommPrescriptionRepository.findByRecommendIdInAndType(recomIds,
                RecomPrescription.TYPE_PHARMACIST_SIGN);

        if (CollectionUtil.isNotEmpty(recomPrescriptions)) {
            pdfUrls = recomPrescriptions.stream().map(recom -> IMG_URL + recom.getPrescriptionPhotoUrl()).collect(Collectors.toList());
        }
        return PrescriptionVO.builder().pdfURL(pdfUrls).build();
    }

    @Override
    public List<TianjinSuperviseRecomVO> tianjinRecomList(Date startDate, Date endDate) throws BusinessException {
        List<TianjinSuperviseRecomVO> result = new ArrayList<>();

        // 查询处方审核信息
        List<RecomAuditLog> recomAuditLogs = recommissionLogRepository.findByAuditTypeAndStatusAndChangedAtBetween(
            RecomAuditLog.AUDIT_TYPE_ARTIFICIAL, RecomAuditLog.AUDIT_STATUS_PASS, startDate, endDate);
        if (CollectionUtil.isEmpty(recomAuditLogs)) {
            return null;
        }
        Map<Long, Date> recomAuditLogMap =
            recomAuditLogs.stream().collect(Collectors.toMap(RecomAuditLog::getRecomId, RecomAuditLog::getChangedAt));

        // 查询处方信息
        List<Long> recomIds = recomAuditLogs.stream().map(RecomAuditLog::getRecomId).collect(Collectors.toList());
        List<MedicationRecom> medicationRecoms = medicationRecomRepository.findByIdIn(recomIds);

        // 处方药品明细
        List<MedicationRecomDetail> recomDetails = medicationRecomDetailRepository.findByRecommendIdIn(recomIds);
        Map<Long, List<MedicationRecomDetail>> recomDetailMap =
            recomDetails.stream().collect(Collectors.groupingBy(MedicationRecomDetail::getRecommendId));

        // 药品信息
        Set<Long> productIds = recomDetails.stream().map(MedicationRecomDetail::getPid).collect(Collectors.toSet());
        List<MedicineBO> medicines = b2cFeignClient.medicineList(productIds);
        Map<Long, MedicineBO> medicineMap =
            medicines.stream().collect(Collectors.toMap(MedicineBO::getProductId, m -> m));

        // 推荐用药处方诊断记录
        List<DrMedicationRecomDiagnosis> recomDiagnoses =
            medicationRecomDiagnosisRepository.findByRecommendIdIn(recomIds);
        Map<Long, List<DrMedicationRecomDiagnosis>> recomDiagnosisMap =
            recomDiagnoses.stream().collect(Collectors.groupingBy(DrMedicationRecomDiagnosis::getRecommendId));

        // 标准诊断信息
        List<Long> diagnoseIds =
            recomDiagnoses.stream().map(diagnose -> diagnose.getDiagnosisId()).collect(Collectors.toList());
        List<DrStandardDiagnosis> diagnoses = standardDiagnosisRepository.findByIdIn(diagnoseIds);
        Map<Long, DrStandardDiagnosis> diagnosisMap =
            diagnoses.stream().collect(Collectors.toMap(DrStandardDiagnosis::getId, e -> e));

        // 处方信息
        List<DrMedicationRecomInfo> medicationRecomInfos = medicationRecomInfoRepository.findByRecommendIdIn(recomIds);
        Map<Long, DrMedicationRecomInfo> medicationRecomInfosMap =
            medicationRecomInfos.stream().collect(Collectors.toMap(DrMedicationRecomInfo::getRecommendId, e -> e));

        // 获取病情记录信息（处方只能由视频问诊发送，视频问诊发起不需要病情病例）
        // Set<String> caseIds = medicationRecomInfos.stream().filter(recomInfo -> recomInfo.getCaseId() !=
        // null).map(DrMedicationRecomInfo::getCaseId).collect(Collectors.toSet());
        // Map<String, String> caseMap = getDiseaseContentMap(caseIds, 1);
        // Set<String> diseaseIds = medicationRecomInfos.stream().filter(recomInfo -> recomInfo.getDiseaseId() !=
        // null).map(DrMedicationRecomInfo::getDiseaseId).collect(Collectors.toSet());
        // Map<String, String> diseaseMap = getDiseaseContentMap(diseaseIds, 2);

        // 就诊人信息
        Set<Long> inquirerIds =
            medicationRecoms.stream().map(MedicationRecom::getInquirerId).collect(Collectors.toSet());
        List<PatientInquirerBO> inquirers = patientFeignClient.getPatientInquirer(new ArrayList<>(inquirerIds));
        Map<Long, PatientInquirerBO> inquirerMap =
            inquirers.stream().collect(Collectors.toMap(PatientInquirerBO::getInquirerId, i -> i));

        // 医生信息
        Set<Long> doctorIds =
            medicationRecomInfos.stream().map(DrMedicationRecomInfo::getDoctorId).collect(Collectors.toSet());
        Map<Long, DoctorBO> doctorMap = doctorFeignClient.getDoctors(doctorIds);

        // 药师ID列表
        List<Long> pharmacistIds =
            medicationRecomInfos.stream().map(info -> info.getPharmacistId()).collect(Collectors.toList());
        // 批量获取药师信息
        List<PharmacistInfoBO> pharmacistInfoBOS = pharmacistFeignClient.getPharmacistInfoList(pharmacistIds);
        Map<Long, PharmacistInfoBO> pharmacistInfoMap =
            pharmacistInfoBOS.stream().collect(Collectors.toMap(PharmacistInfoBO::getId, e -> e));

        // 处方签名文件
        List<RecomPrescription> recomPrescriptions =
            recommPrescriptionRepository.findByRecommendIdInAndType(recomIds, RecomPrescription.TYPE_PHARMACIST_SIGN);
        Map<Long, RecomPrescription> recomPrescriptionMap =
            recomPrescriptions.stream().collect(Collectors.toMap(RecomPrescription::getRecommendId, e -> e));

        // 处方订单信息
        List<OrderBO> orderList = b2cFeignClient.orderlist(recomIds);
        Map<Long, OrderBO> orderMap = orderList.stream().collect(Collectors.toMap(OrderBO::getRecomId, o -> o));

        // 根据处方获取视频消息信息
        Set<Long> videoConsultIds =
            medicationRecoms.stream().map(MedicationRecom::getVideoConsultId).collect(Collectors.toSet());
        // 获取视频问诊信息
        List<VideoConsultBO> videoConsults = videoConsultFeignClient.getVideoConsults(videoConsultIds);
        Map<Long, VideoConsultBO> videoConsultMap =
            videoConsults.stream().collect(Collectors.toMap(VideoConsultBO::getId, Function.identity()));

        // 拼接处方信息
        if (CollectionUtil.isNotEmpty(medicationRecoms)) {
            for (MedicationRecom recom : medicationRecoms) {
                DrMedicationRecomInfo medicationRecomInfo = medicationRecomInfosMap.get(recom.getId());
                PharmacistInfoBO pharmacistInfo = pharmacistInfoMap.get(medicationRecomInfo.getPharmacistId());
                if (pharmacistInfo == null) {
                    continue;
                }
                // 药师审方时间
                Date checkDate = recomAuditLogMap.get(recom.getId());
                VideoConsultBO videoConsultBO = videoConsultMap.get(recom.getVideoConsultId());
                if (videoConsultBO == null) {
                    continue;
                }
                DoctorBO doctor = doctorMap.get(recom.getDoctorId());
                PatientInquirerBO inquirer = inquirerMap.get(recom.getInquirerId());
                TianjinSuperviseRecomVO vo =
                    TianjinSuperviseRecomVO.builder().id(recom.getId()).sessionId(videoConsultBO.getOrderSn())
                        .createdAt(recom.getCreatedAt()).effectiveDays(7).patientId(inquirer.getInquirerId())
                        .patientName(inquirer.getName()).patientGender(inquirer.getGender())
                        .patientIdCardNo(inquirer.getIdCard()).patientAge(inquirer.getAgeYear())
                        .patientPhone(inquirer.getPhone()).guardianIdCard(inquirer.getGuardianIdCard())
                        .guardianName(inquirer.getGuardianName()).doctorId(doctor.getId()).doctorName(doctor.getName())
                        .doctorIdCard(doctor.getIdCard()).departmentId(doctor.getDepartmentId())
                        .departmentName(medicationRecomInfo.getDepartmentName()).pharmacistId(pharmacistInfo.getId())
                        .pharmacistName(pharmacistInfo.getName()).pharmacistIdCard(pharmacistInfo.getIdCard())
                        .pdfUrl(null != recomPrescriptionMap.get(recom.getId())
                            ? IMG_URL + recomPrescriptionMap.get(recom.getId()).getPrescriptionPhotoUrl() : null)
                        .recipeType(SuperviseConstant.Tianjin.RECIPE_TYPE_WESTERN_MEDICINE)
                        .isPay(SuperviseConstant.Tianjin.UNPAID)
                        .verificationStatus(SuperviseConstant.Tianjin.VERIFICATION_STATUS_NO).rationalFlag(0)
                        .recipeUniqueID(recom.getSerialNumber()).startDate(recom.getCreatedAt())
                        .diseasesContent(videoConsultBO.getConditionDesc()).checkDate(checkDate).build();
                // 需要判断如果为0，则为未支付，其他情况为已支付
                if (recom.getStatus() != null && recom.getStatus() != Constants.RecomStatusEunm.NOT_BUY.getCode()
                    && recom.getStatus() != Constants.RecomStatusEunm.ALREADY_ORDER.getCode()) {
                    vo.setIsPay(SuperviseConstant.Tianjin.PAID);
                }

                // 如果当前处方订单为已签收状态，代表处方已核销
                OrderBO order = orderMap.get(recom.getId());
                if (order != null && order.getOrderStatus() == 7) {
                    // 配置处方核销信息
                    vo.setVerificationStatus(SuperviseConstant.Tianjin.VERIFICATION_STATUS_YES);
                    vo.setDeliveryType(SuperviseConstant.Tianjin.DELIVERY_TYPE_WAREHOUSE_LOGISTICS);
                    vo.setVerificationTime(order.getChangedAt());
                    vo.setDeliveryFirm(order.getChangedBy());
                    vo.setDeliveryPeople(order.getChangedBy());
                    vo.setDeliveryFee(order.getFreight());
                    vo.setTradeNo(order.getOrderSn());
                    vo.setStartDate(order.getChangedAt());
                }

                // 拼接诊断信息
                if (null != recomDiagnosisMap.get(recom.getId())) {

                    List<DrMedicationRecomDiagnosis> diagnosisList = recomDiagnosisMap.get(recom.getId());
                    vo.setDiagnosis(diagnosisList.stream().map(diag -> {
                        DrStandardDiagnosis diagno = diagnosisMap.get(diag.getDiagnosisId());
                        return SuperviseDiagnosisVO.builder().id(diagno.getId()).code(diagno.getMainCode())
                            .name(diagno.getName()).build();
                    }).collect(Collectors.toList()));
                }

                // 拼接药品信息
                List<SuperviseProductVO> products = new ArrayList<>();
                List<MedicationRecomDetail> details = recomDetailMap.get(recom.getId());
                if (CollectionUtil.isEmpty(details)) {
                    continue;
                }
                // 处方药品用药时间
                Map<Long, Integer> medicateDayMap = recomDays(details);
                // 药品用药最长时间
                Integer maxMedicateDay = medicateDayMap.values().stream().max(Comparator.comparing(v -> v)).get();
                vo.setEndDate(DateUtil.addDays(vo.getStartDate(), maxMedicateDay));

                details.forEach(detail -> {
                    MedicineBO medicine = medicineMap.get(detail.getPid());
                    SuperviseProductVO productVO = SuperviseProductVO.builder().skuId(detail.getSkuId())
                        .name(detail.getName()).commonName(detail.getCommonName()).dosageCount(detail.getDosageCount())
                        .dosageCycleUnit(detail.getDosageCycleUnit()).dosageCycle(detail.getDosageCycle().toString())
                        .eachDosageCount(detail.getEachDosageCount()).eachDoseUnit(detail.getEachDoseUnit())
                        .drugCycle(detail.getDrugCycle()).drugCycleUnit(detail.getDrugCycleUnit())
                        .usageMethod(detail.getUsageMethod()).quantity(detail.getQuantity())
                        .quantityUnit(detail.getQuantityUnit()).salePrice(detail.getSalePrice())
                        .totalPrice(detail.getSalePrice() * detail.getQuantity()).usageTime(detail.getUsageTime())
                        .productionEnterprise(medicine.getProductionEnterprise())
                        .otcFlag(medicine.getNmpaType() == 2 ? SuperviseConstant.Tianjin.OTC_FLAG_YES
                            : SuperviseConstant.Tianjin.OTC_FLAG_NO)
                        .useDays(medicateDayMap.get(detail.getId())).build();
                    products.add(productVO);
                });

                vo.setProducts(products);
                vo.setTotalPrice(details.stream()
                    .collect(Collectors.summingInt(detail -> detail.getQuantity() * detail.getSalePrice())));

                result.add(vo);
            }
        }

        return result;
    }

    public Map<Long, Integer> recomDays(List<MedicationRecomDetail> details) {
        Map<Long, Integer> result = new HashMap<>();
        for (MedicationRecomDetail detail : details) {
            Double drugCycle = detail.getDrugCycle();
            String dosageCycleUnit = detail.getDosageCycleUnit();
            switch (dosageCycleUnit) {
                case "周":
                    drugCycle *= 7;
                    break;
                case "月":
                    drugCycle *= 30;
                    break;
            }
            result.put(detail.getId(), (int)Math.ceil(Optional.ofNullable(drugCycle).orElse(1D)));
        }
        return result;
    }

    @Override
    public Map<Long, Set<String>> recomDiagnosis(String sessionIds, String recomIds) {
        List<MedicationRecom> medicationRecom;
        List<Long> ids;
        Map<Long, String> recomMap;
        if (StringUtils.isNotEmpty(sessionIds)) {
            ids = Arrays.asList(sessionIds.split(",")).stream().filter(id -> StringUtils.isNotBlank(id))
                .map(id -> Long.valueOf(id)).collect(Collectors.toList());
            medicationRecom = medicationRecomRepository.findBySessionIdIn(ids);
            recomMap = medicationRecom.stream().collect(Collectors.groupingBy(MedicationRecom::getSessionId,
                Collectors.mapping(MedicationRecom::getDiagnosis, Collectors.joining(","))));
        } else {
            ids = Arrays.asList(recomIds.split(",")).stream().filter(id -> StringUtils.isNotBlank(id))
                .map(id -> Long.valueOf(id)).collect(Collectors.toList());
            medicationRecom = medicationRecomRepository.findByIdIn(ids);
            recomMap = medicationRecom.stream().filter(mr -> StringUtils.isNotEmpty(mr.getDiagnosis()))
                .collect(Collectors.toMap(MedicationRecom::getId, MedicationRecom::getDiagnosis));
        }

        Map<Long, Set<String>> diagnosisMap = new HashMap<>();
        recomMap.forEach((k, v) -> {
            diagnosisMap.put(k, new HashSet<>(Arrays.asList(v.split(","))));
        });
        return ids.stream().collect(
            Collectors.toMap(id -> id, id -> Optional.ofNullable(diagnosisMap.get(id)).orElse(new HashSet<>())));
    }
}
